package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单任务
 * @author ghy
 * @version 1.0.1
 * @date 2023-05-02 09:32:55
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时订单
     *      企业都是使用延迟任务
    */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder(){
        log.warn("处理超时订单---->");
        //未支付
        LocalDateTime orderTime = LocalDateTime.now().minusMinutes(15);
        List<Orders> ordersList = orderMapper.getByOrderTimeAndStatus(orderTime, Orders.PENDING_PAYMENT);
        if(ordersList != null && ordersList.size() > 0) {
            //修改订单状态
            ordersList.stream().forEach(item -> {
                item.setStatus(Orders.CANCELLED);
                item.setCancelTime(LocalDateTime.now());
                item.setCancelReason("超时未支付，订单取消！！");
                orderMapper.update(item);
            });
        }
    }

    /**
     * 处理派送中订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    //@Scheduled(cron = "0 55 * * * ?")
    public void processDeliveryOrder(){
        log.warn("处理派送中订单---->");
        List<Orders> ordersList = orderMapper.getByOrderTimeAndStatus(LocalDateTime.now(), Orders.DELIVERY_IN_PROGRESS);
        if(ordersList != null && ordersList.size() > 0) {
            //修改订单状态
            ordersList.stream().forEach(item -> {
                item.setStatus(Orders.COMPLETED);
                orderMapper.update(item);
            });
        }
    }

}
